#include "CurrentUser.h"

QSqlDatabase db3 = QSqlDatabase::database("KFC");    //获取指向数据库的连接

//CurrentUser::CurrentUser(QObject *parent) : QObject(parent)
//{

//}

void CurrentUser::createCurrentUserTable(){
    QSqlQuery query(db3);

    /**
      * @leiteorz
      * name:用户名
      * category:判断是买家还是商家,0为客户,1为商家
      * account:用户的账号
      * password:用户的密码
      * phone_num:用户的手机号
      */
    const QString cmd = R"(
                        create table current_user(id integer primary key,
                                                name varchar(50),
                                                category integer,
                                                account varchar(50),
                                                password varchar(50),
                                                phone_num varchar(50));
                        )";

    query.exec(cmd);    //执行建表语句
}

//插入当前用户
void CurrentUser::insertCurrentUser(User u){
        QSqlQuery query(db3);
        //数据插入(预分配空间)
        query.prepare("insert into current_user values(?,?,?,?,?,?);");
        //绑定要插入的值
        query.bindValue(1,u.name);
        query.bindValue(2,u.category);
        query.bindValue(3,u.account);
        query.bindValue(4,u.password);
        query.bindValue(5,u.phone_num);
        //调用exec()函数在query中插入上述值
        query.exec();
}

//查询当前用户
User CurrentUser::queryCurrentUser(){
    QSqlQuery query(db3);

    const QString cmd = "select * from current_user where id=1;";
    query.exec(cmd);

    QString name;
    int category;
    QString account;
    QString password;
    QString phone_num;

    while(query.next()){
        name = query.value(1).toString();
        category = query.value(2).toInt();
        account = query.value(3).toString();
        password = query.value(4).toString();
        phone_num = query.value(5).toString();
    }

    User *u = new User(name,category,account,password,phone_num);

    return *u;
}

//删除当前用户
void CurrentUser::deleteCurrentUser(){
    QSqlQuery query(db3);

    const QString cmd = "delete from current_user where id=1;";

    query.exec(cmd);
}

//修改当前用户
void CurrentUser::updateCurrentUser(QString name, QString phone_num){
    QSqlQuery query(db3);
    //数据修改
    query.exec("update current_user set name = '" + name + "' where id = 1");
    query.exec("update current_user set phone_num = '" + phone_num + "' where id = 1");
}
